import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store/'

Vue.use(VueRouter)

const router = new VueRouter({
  routes,
  linkActiveClass: 'active',
  scrollBehavior () {
    return { x: 0, y: 0 }
  }
})

const loaded = {}
router.beforeEach((to, from, next) => {
  const token = store.state.authorization.token
  const pending = store.state.authorization.pending
  const auths = store.state.authorization.permission
  const meta = to.meta || {}

  console.log(`route from ${from.name} -> ${to.name}, pending: ${pending}, private: ${meta.private}`)

  if (!from.name && to.name === '404') {
    return next({path: '/'})
  }
  if (!from.name && !token && to.name === 'loading') {
    return next({path: '/'})
  }
  if (!from.name && to.name === 'access-denied') {
    return next({path: '/'})
  }

  if (meta.private === true && !token) {
    return next({name: 'login', query: {backward: to.fullPath}})
  }
  if (pending && meta.private === true && to.name !== 'loading') {
    return next({name: 'loading', query: {backward: to.fullPath}})
  }

  if (to.meta.auth && !auths.includes(to.meta.auth)) {
    return next({name: 'access-denied', query: {backward: to.fullPath}})
  }

  if (to.matched.length === 0) {
    return next({name: '404'})
  }

  if (loaded[to.name] !== true) {
    window.ym && window.ym.loading && window.ym.loading(true)
  }
  next()
})

router.beforeResolve((to, from, next) => {
  loaded[to.name] = true
  next()
})

router.afterEach((to, from) => {
  window.ym && window.ym.loading && window.ym.loading(false)
})

router.onError(res => {
  window.ym && window.ym.loading && window.ym.loading(false)
  console.log('on router error', res)
  window.ym && window.ym.onRouterError && window.ym.onRouterError(res)
})

export default router
